package com.example.wan1.view.home;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import com.example.wan1.R;
import com.example.wan1.adapter.ProjectListAdapter;
import com.example.wan1.base.fragment.SimpleFragment;
import com.example.wan1.bus.RxBus;
import com.example.wan1.constant.Constants;
import com.example.wan1.event.CollectEvent;
import com.example.wan1.model.ArticleBean;
import com.example.wan1.model.ProjectCategoryBean;
import com.example.wan1.model.common.CommonResList;
import com.example.wan1.utils.AppUtils;
import com.example.wan1.view.collect.HandleCollectTool;
import com.example.wan1.view.login.UserManager;
import com.example.wan1.view.project.ProjectContract;
import com.example.wan1.view.project.ProjectPresenter;
import com.example.wan1.view.web.JumpTool;
import com.scwang.smart.refresh.header.MaterialHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.List;

import javax.inject.Inject;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;

/***
 * @Author: zxd
 * @CreateDate: 2020/6/28 14:14
 * @Description: 最新项目
 */
public class PerProjectFragment extends SimpleFragment implements ProjectContract.View,
        OnLoadMoreListener, OnRefreshListener {

    @BindView(R.id.srlheader)
    MaterialHeader mSrlheader;
    @BindView(R.id.project_rv)
    RecyclerView mProjectRv;
    @BindView(R.id.srl)
    SmartRefreshLayout mSrl;

    @Inject
    ProjectPresenter mPresenter;
    @Inject
    List<ArticleBean> mData;
    @Inject
    ProjectListAdapter mAdapter;

    private int id;
    private String type;
    private int page = 1;

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        mProjectRv.postDelayed(() -> {
            if (Constants.PROJECT_NORMAL_TYPE.equals(type)) {
                mPresenter.getProjectList(page, id);
            } else {
                mPresenter.getProjectNewList(page);
            }
            mSrl.finishLoadMore(true);
        }, 200);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mData.clear();
        mProjectRv.postDelayed(() -> {
            if (Constants.PROJECT_NORMAL_TYPE.equals(type)) {
                mPresenter.getProjectList(1, id);
            } else {
                mPresenter.getProjectNewList(0);
            }
            mSrl.finishRefresh(true);
        }, 200);
    }

    @Override
    public void onSuccess(CommonResList<ArticleBean> data) {
        hideLoading();
        if (data.getDatas().size() > 0) {
            mSrl.setEnableRefresh(true);
            mSrl.setEnableLoadMore(true);
        }

        if (data.isOver()) {
            mAdapter.loadMoreEnd();
            if (mAdapter.getFooterLayoutCount() == 0) {
                View footer = LayoutInflater.from(mContext).inflate(R.layout.loadmore_view, null);
                mAdapter.addFooterView(footer);
            }
            mSrl.setEnableLoadMore(false);
        }
        if (data.getDatas().size() == 0) return;
        mAdapter.addData(data.getDatas());
        if (Constants.PROJECT_NORMAL_TYPE.equals(type)) {
            page = data.getCurPage() + 1;
        } else {
            page = data.getCurPage();
        }
    }

    @Override
    public void onFailure(String msg) {
        showError();
    }

    @Override
    public void onCategoryProject(List<ProjectCategoryBean> data) {

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //mData = new ArrayList<>();
    }

    @Override
    protected void initData() {
        //Log.i("zxd", "initData: PerProjectFragment");
        //请求数据
        showLoading();
        if (Constants.PROJECT_NORMAL_TYPE.equals(type)) {
            mPresenter.getProjectList(1, id);
        } else {
            mPresenter.start();
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Bundle arguments = getArguments();
        id = arguments.getInt(Constants.PROJECT_ID_PARAM, 0);
        type = arguments.getString(Constants.PROJECT_TYPE_PARAM);
    }

    @Override
    protected void initView() {
        //mSrlheader.setColorSchemeResources(R.color.qc_green);

        //mAdapter = new ProjectListAdapter(R.layout.project_list_item, mData, type);
        mProjectRv.setAdapter(mAdapter);
        mProjectRv.setLayoutManager(new LinearLayoutManager(mContext));

        mSrl.setOnLoadMoreListener(this);
        mSrl.setOnRefreshListener(this);

        mSrl.setEnableRefresh(false);
        mSrl.setEnableLoadMore(false);

        mAdapter.setOnItemClickListener((baseQuickAdapter, view1, i) -> {
            JumpTool.goWeb(mContext, mData.get(i).getTitle(), mData.get(i).getLink());
            HandleCollectTool.getInstance().setInfo(mData.get(i), i, Constants.PROJECT);
        });

        mAdapter.setOnItemChildClickListener((baseQuickAdapter, view, i) -> {
            switch (view.getId()) {
                case R.id.project_list_collect: {
                    if (!UserManager.getInstance().isLogin()){
//                    if (!AppUtils.isLogin()) {
                        JumpTool.goLogin(getActivity());
                        return;
                    }
                    ArticleBean articleBean = mData.get(i);
                    HandleCollectTool.getInstance().setInfo(articleBean, i, Constants.PROJECT);
                    ImageView iv = view.findViewById(R.id.project_list_collect);
                    if (articleBean.isCollect()) {
                        HandleCollectTool.getInstance().cancelList();
                        iv.setImageResource(R.mipmap.heart_gray);
                    } else {
                        HandleCollectTool.getInstance().collectIn();
                        iv.setImageResource(R.mipmap.heart_red);
                    }
                }
                break;
            }
        });

        mProjectRv.addOnScrollListener(mOnScrollListener);
    }

    @Override
    protected int initLayoutRes() {
        return R.layout.fragment_per_project;
    }

    public PerProjectFragment newInstance(String type, int id) {
        PerProjectFragment baseFragment = new PerProjectFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(Constants.PROJECT_ID_PARAM, id);
        bundle.putString(Constants.PROJECT_TYPE_PARAM, type);
        baseFragment.setArguments(bundle);
        return baseFragment;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        RxBus.getDefault().subscribeSticky(mContext, new RxBus.Callback<CollectEvent>() {
            @Override
            public void onEvent(CollectEvent collectEvent) {
                if (Constants.PROJECT.equals(collectEvent.getType()))
                    notifyItemCollect();
            }
        });
        RxBus.getDefault().subscribe(mContext, new RxBus.Callback<String>() {
            @Override
            public void onEvent(String s) {
                if (s.equals("cancelArticle")) {
                    mData.clear();
                    mPresenter.start();
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unregister(mContext);
    }

    private void notifyItemCollect() {
        if (mProjectRv.getAdapter() == null)
            mAdapter.bindToRecyclerView(mProjectRv);
        int pos = HandleCollectTool.getInstance().getPosition();
        mAdapter.notifyItemChanged(pos);
    }
}
